package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import java.util.Date;
import java.util.Vector;

public class ClientKeys {
	private static final long MILLSECS_PER_DAY = 100*60*60*24;
	private static String filename = "src//ssl//serverData//clientKeys";
	public Vector<ClientKey> keys;
	
	

	public int inList(String username) {
		for (int i = 0; i < keys.size(); i++) {
			if (keys.get(i).username.equals(username)) {
				return i;
			}
		}
		return -1;

	}

	public void add(String username, KeyPair key, String pwhash) {
		ClientKey ckey = new ClientKey();
		ckey.key = key;
		ckey.username = username;
		ckey.pwhash = pwhash;
		ckey.date = new Date();

		keys.add(ckey);
	}

	public void writeKeys() {
		OutputStream fos = null;

		try {
			fos = new FileOutputStream(filename);
			ObjectOutputStream o = new ObjectOutputStream(fos);
			o.writeObject(keys);
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void readKeys() {
		InputStream fis = null;

		try {
			File file = new File(filename);
			if(file.exists()) {
				fis = new FileInputStream(filename);
				ObjectInputStream o = new ObjectInputStream(fis);
				keys = (Vector<ClientKey>) o.readObject();
				
				// Nur im Programm abgelaufene Pws löschen, sicherheitshalber in Datei lassen!
				for(int i=0; i<keys.size();i++) {
					Date keydate = keys.get(i).date;
					
					long deltaDays = ( new Date().getTime() - keydate.getTime() )/ MILLSECS_PER_DAY;
					if(deltaDays > 100) {
						keys.remove(i);
					}
				}
			} else
				keys = new Vector<ClientKey>();
			

		} catch (IOException e) {
			System.err.println(e);
		} catch (ClassNotFoundException e) {
			System.err.println(e);
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
	}
}
